<?php
// 消息类
class MessageAction extends CommonAction {
    /**
     * [sendMsgHtml description]发送信息催促
     * @return [type] [description]
     */
    public function sendMsgHtml(){
        $msg_to=I('msg_to');
        $msg_from=session('employe_id');
        $msg_title=I('msg_title');
        $msg_content=I('msg_content');
        $result=$this->sendMsgLock($msg_to,$msg_from,$msg_title,$msg_content);
        echo $result;
    }
	/**
     * [sendMsg description]发送消息
     * @param  [type] $msg_to      [description]
     * @param  [type] $msg_from    [description]
     * @param  [type] $msg_title   [description]
     * @param  [type] $msg_content [description]
     * @return [type]              [description]
     */
    public function sendMsg($msg_to,$msg_from,$msg_title,$msg_content){
        $msg=M('Message');
        $msg->msg_to=$msg_to;
        $msg->msg_from=$msg_from;       
        $msg->msg_title=$msg_title;
        $msg->msg_content=$msg_content;
        $msg->msg_ifread=0;
        $msg->msg_time=time();
        if($msg->add()){
            return 'ok';
        }
        else{
            return 'no';
        }
    }

    /**
     * [sendMsgLock description]发送消息锁定功能
     * @param  [type] $msg_to      [description]
     * @param  [type] $msg_from    [description]
     * @param  [type] $msg_title   [description]
     * @param  [type] $msg_content [description]
     * @return [type]              [description]
     */
    public function sendMsgLock($msg_to,$msg_from,$msg_title,$msg_content){
        if ($this->LockMsg(I('process_num')) == false)
        {
            return 'later';
        }

        return $this->sendMsg($msg_to,$msg_from,$msg_title,$msg_content);
    }


    /**
     * [setreaded description]标记已读
     * @param  [type] $employe_id [description]
     * @return [type]             [description]
     */
    public function setreaded(){
        $employe_id=session('employe_id');
        $msg=M('Message');
        $data['msg_ifread']=1;
        $msg->where("msg_to='".$employe_id."'")->save($data);
    }
    
    /**
     * [getMsgCount description]获取当前用户消息数量
     * @return [type] [description]
     */
    public function getMsgCount(){
        $employe_id=session('employe_id');
        $msg=M('Message');
        $count=$msg->where("msg_to='".$employe_id."' and msg_ifread=0")->count();
        return $count;
    }

    /**
     * [MsgList description]消息列表跳转
     */
    public function MsgList(){
        $this->display("Message:msgList");
    }

    /**
     * [MsgListData description]获取消息列表
     * @return [type] [description]
     */
    public function MsgListData(){
        $result = array();
        $result['total'] = $this->getMsgListCount();
        $result['rows'] = $this->getMsgList();
        $this->setreaded();
        echo json_encode($result);
    }

    /**
     * 获取列表
     */
    public function getMsgList()
    {
        import("ORG.Util.Page");
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
        $employe_id=session('employe_id');
        $msg=M('Message');
        $result=array();
        $data=$msg->where("msg_to='".$employe_id."'")->page($page,$rows)->order("msg_ifread asc,msg_time desc")->select();
        foreach ($data as $value) {
        	$value['msg_from']=$this->getOneEmployeName($value['msg_from']);
            $result[]=$value;
        }
        return $result;
    }
    
    /**
     * 获取列表数量
     */
    public function getMsgListCount()
    {   
    	$employe_id=session('employe_id');
        $msg=M('Message');
        $result=$msg->where("msg_to='".$employe_id."'")->count();
        return $result;
    }


    /*--------------------------------
    功能:     HTTP接口 发送短信
    修改日期:   2011-03-04
    说明:     http://api.sms.cn/mt/?uid=用户账号&pwd=MD5位32密码&mobile=号码&mobileids=号码编号&content=内容
    状态:
        100 发送成功
        101 验证失败
        102 短信不足
        103 操作失败
        104 非法字符
        105 内容过多
        106 号码过多
        107 频率过快
        108 号码内容空
        109 账号冻结
        110 禁止频繁单条发送
        112 号码不正确
        120 系统升级
    --------------------------------
    $http = 'http://api.sms.cn/mt/';        //短信接口
    $uid = '53338';                         //用户账号
    $pwd = 'c7idm3';                            //密码
    $mobile  = '18042016255';   //号码
    $mobileids   = '1804201625512345666688';    //号码唯一编号
    $content = '您的验证码是：377882，有效期为10分钟。如非本人操作，可不用理会。【云信使】';     //内容
    //即时发送
    $res = sendSMS($http,$uid,$pwd,$mobile,$content,$mobileids);
    echo $res;*/

    //定时发送
    /*
    $time = '2010-05-27 12:11';
    $res = sendSMS($uid,$pwd,$mobile,$content,$time);
    echo $res;
    */
    function sendSMS($mobile,$content,$mobileids,$http='http://api.sms.cn/mtutf8/',$uid='53338',$pwd='c7idm3',$time='',$mid='')
    {
        return "发送成功!";
        /*$data = array
            (
            'uid'=>$uid,                    //用户账号
            'pwd'=>md5($pwd.$uid),          //MD5位32密码,密码和用户名拼接字符
            'mobile'=>$mobile,              //号码
            'content'=>$content,            //内容
            'mobileids'=>$mobileids,
            'time'=>$time,                  //定时发送
            );
        $re= $this->postSMS($http,$data);          //POST方式提交
        if($this->checkstr($re))
        {
            return "发送成功!";
        }
        else 
        {
            return "发送失败!";
        }*/
    }

    /**
     * [sendSMSLock description]发送短信
     * @return [type] [description]
     */
    public function sendSMSLock(){
        if ($this->LockMsM(I('process_num')) == false)
        {
            return 'later';
        }
        $msg_from=session('employe_id');
        $msg_title=I('msg_title');
        $msg_content=I('msg_content');
        $employe_name=$this->getOneEmployeName($msg_from);
        
        $mobile=I('employe_phone');
        $content=$employe_name.'的'.$msg_title.$msg_content.'【来自丽丰OA系统】';
        $mobileids=$mobile.strval(time());
        return $this->sendSMS($mobile,$content,$mobileids);
        
    }

    /**
     * [sendSMSHtml description]发送短信催促
     * @return [type] [description]
     */
    public function sendSMSHtml(){
        $result=$this->sendSMSLock();
        echo $result;
    }


    public function checkstr($str){
        $needle = '100';
        $tmparray = explode($needle,$str);
        if(count($tmparray)>1){
            return true;
        }
        else{
            return false;
        }
    }

    /**
     * [postSMS description]发送短信
     * @param  [type] $url  [description]
     * @param  string $data [description]
     * @return [type]       [description]
     */
    public function postSMS($url,$data='')
    {
        $row = parse_url($url);
        $host = $row['host'];
        $port = $row['port'] ? $row['port']:80;
        $file = $row['path'];
        while (list($k,$v) = each($data)) 
        {
            $post .= rawurlencode($k)."=".rawurlencode($v)."&"; //转URL标准码
        }
        $post = substr( $post , 0 , -1 );
        $len = strlen($post);
        $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
        if (!$fp) {
            return "$errstr ($errno)\n";
        } else {
            $receive = '';
            $out = "POST $file HTTP/1.1\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Content-type: application/x-www-form-urlencoded\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Content-Length: $len\r\n\r\n";
            $out .= $post;      
            fwrite($fp, $out);
            while (!feof($fp)) {
                $receive .= fgets($fp, 128);
            }
            fclose($fp);
            $receive = explode("\r\n\r\n",$receive);
            unset($receive[0]);
            return implode("",$receive);
        }
    }


    /**
     * [LockMsg description]锁定半小时后重新发送
     * @param [type] $process_num [description]
     */
    public function LockMsg($process_num) {
        //return false;
        $ip = get_client_ip().$process_num.'Msg';
        $obj = S($ip);

        if (empty($obj)) {
            $obj = array(
                $ip => array(
                    'state' => 'lock',
                    'count' => 1,
                    'times' => time()
                ) 
            );
            S($ip, $obj);
            return true;
        }
        else {
                if (time() - $obj[$ip]['times'] >= 30 * 60) {
                    $obj = array(
                        $ip => array(
                            'state' => 'lock',
                            'count' => 1,
                            'times' => time()
                        ) 
                    );
                    S($ip, $obj);
                    return true;
                }
                return false;
        }
    }

    /**
     * [LockMsM description]锁定半小时后重新发送
     * @param [type] $process_num [description]
     */
    public function LockMsM($process_num) {
        //return false;
        $ip = get_client_ip().$process_num.'Msm';
        $obj = S($ip);

        if (empty($obj)) {
            $obj = array(
                $ip => array(
                    'state' => 'lock',
                    'count' => 1,
                    'time' => time()
                ) 
            );
            S($ip, $obj);
            return true;
        }
        else {
                if (time() - $obj[$ip]['time'] >= 30 * 60) {
                    $obj = array(
                        $ip => array(
                            'state' => 'lock',
                            'count' => 1,
                            'time' => time()
                        ) 
                    );
                    S($ip, $obj);
                    return true;
                }
                return false;
        }
    }

    /**
     * 解除锁定
     */
    public function UnLock() {
        $ip = get_client_ip();
        S($ip, null);
    }


}